from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from web.forms.project import ProjectModelForm
from web import models
from utils.tencent.cos import create_bucket
import time

#
# def project_list(request):
#     """
#     展示项目
#     :param request:
#     :return:
#     """
#
#     if request.method == 'GET':
#
#         """
#         要求前端页面展示出：
#             1、重点标记的项目包含两部分内容：
#                 1)、我创建的项目；
#                 2)、我参与的项目；
#
#             2、我创建的所有项目；
#
#             3、我参与的所有项目
#         """
#
#         project_list = {'my': [], 'join': [], 'star': []}
#
#         my_project = models.Project.objects.filter(creator=request.tracer.user)
#
#         join_project = models.ProjectUser.objects.filter(user=request.tracer.user)
#
#         for row in my_project:
#             if row.star:
#                 project_list['star'].append({'value': row, 'type': 'my'})
#             else:
#                 project_list['my'].append(row)
#
#         for item in join_project:
#             if item.star:
#                 project_list['star'].append({'value': item.project, 'type': 'join'})
#             else:
#                 project_list['join'].append(item.project)
#
#         form = ProjectModelForm(request)
#         return render(request, 'project_list.html', {'form': form, 'project_list': project_list})
#
#     form = ProjectModelForm(request, request.POST)
#     if form.is_valid():
#         # 用户输入的内容通过校验后，需要在数据库中保存 '项目名'、'项目底色'、'项目描述'、'项目创建者' 四个字段的数据
#         # '项目名'、'项目底色'、'项目描述' 这三个字段的数据已经包含在form对象中了
#         # 故需要在form对象中封装 '创建者' creator 此字段的数据
#         form.instance.creator = request.tracer.user
#         # 将以上四个字段的信息保存到数据库中
#         form.save()
#         return JsonResponse({'status': True})
#
#     return JsonResponse({'status': False, 'error': form.errors})
#
#
# def project_star(request, project_type, project_id):
#     """
#     标记重点项目
#     :param request:
#     :return:
#     """
#     if project_type == 'my':
#         # 对当前登录用户所创建的项目做重点标记
#         models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
#
#         return redirect('project_list')
#
#     if project_type == 'join':
#         # 对当前用户所参与的项目做重点标记
#
#         models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
#
#         return redirect('project_list')
#
#     return HttpResponse('请求错误！')
#
#
# def project_unstar(request, project_type, project_id):
#     """
#     取消重点项目的标记
#     :param request:
#     :param project_type:
#     :param project_id:
#     :return:
#     """
#
#     if project_type == 'my':
#         # 取消当前登录用户所重点标记的项目
#         models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
#
#         return redirect('project_list')
#
#     if project_type == 'join':
#         # 取消当前用户重点标记的所参与的项目
#
#         models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
#
#         return redirect('project_list')
#
#     return HttpResponse('请求错误！')

def project_list(request):
    """ 项目列表 """
    if request.method == "GET":
        # GET请求查看项目列表
        """
        1. 从数据库中获取两部分数据
            我创建的所有项目：已星标、未星标
            我参与的所有项目：已星标、未星标
        2. 提取已星标
            列表 = 循环 [我创建的所有项目] + [我参与的所有项目] 把已星标的数据提取

        得到三个列表：星标、创建、参与
        """
        project_dict = {'star': [], 'my': [], 'join': []}

        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        for row in my_project_list:
            if row.star:
                project_dict['star'].append({"value": row, 'type': 'my'})
            else:
                project_dict['my'].append(row)

        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in join_project_list:
            if item.star:
                project_dict['star'].append({"value": item.project, 'type': 'join'})
            else:
                project_dict['join'].append(item.project)

        form = ProjectModelForm(request)
        return render(request, 'project_list.html', {'form': form, 'project_dict': project_dict})

    # POST，对话框的ajax添加项目。
    form = ProjectModelForm(request, data=request.POST)
    if form.is_valid():
        # 为项目创建一个桶
        bucket = f"{request.tracer.user.mobile_phone}-{str(int(time.time()))}-1301485706"
        region = 'ap-beijing'
        create_bucket(bucket, region)

        form.instance.bucket = bucket
        form.instance.region = region
        # 验证通过：项目名、颜色、描述 + creator谁创建的项目？
        form.instance.creator = request.tracer.user
        # 创建项目
        instance = form.save()

        # 新建项目后初始化默认的问题类型(issues_type)
        issues_type_object_list = []
        for item in models.IssuesType.PROJECT_INIT_LIST:
            issues_type_object_list.append(models.IssuesType(project=instance, title=item))

        # 批量添加数据
        models.IssuesType.objects.bulk_create(issues_type_object_list)

        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


def project_star(request, project_type, project_id):
    """ 星标项目 """
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect('project_list')

    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
        return redirect('project_list')

    return HttpResponse('请求错误')


def project_unstar(request, project_type, project_id):
    """ 取消星标 """
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('project_list')

    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
        return redirect('project_list')

    return HttpResponse('请求错误')